package com.qyl.honghengshop.controller.admin;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qyl.honghengshop.common.PageConstant;
import com.qyl.honghengshop.dto.User;
import com.qyl.honghengshop.service.UserService;
import com.qyl.honghengshop.service.impl.UserServiceImpl;
import com.qyl.honghengshop.utils.MD5;

/**
 * 后台登录管理
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/admin")
public class AdminController {

	private UserService userService = new UserServiceImpl();
	
	@RequestMapping("/toLogin")
	public String toLogin(){
		
		return "adminLogin";
	}
	@RequestMapping("/toAdminHome")
	public String toAdminHome(){
		return "adminHome";
	}
	
	/*
	 * 后台登录方法
	 */
	@RequestMapping("/adminLogin")
	@ResponseBody
	public Map<String, String> adminLogin(String username,String password,String code,String online,HttpSession session) throws Exception{
		
		Map<String, String> map = new HashMap<String, String>();
		
		//从session中获得验证码
		String adminCode = (String) session.getAttribute(PageConstant.AUTH_CODE);
		
		if(adminCode.equals(code)){
			
			//把密码转成md5
			String newPwd = MD5.getMD5(password);
			
			//验证码相同，从数据库获得用户
			User user = userService.getUserByUserIdAndPwd(username, newPwd);
			if(null !=user){
				
				if(user.getActive_status() == 1){					
					if(user.getRole()>1){
						session.setAttribute(PageConstant.SESSION_USER, user);
						map.put("status", "success");
					}else{
						//用户权限不足
						map.put("status", "fail");
						map.put(PageConstant.TIP, "用户权限不足");
					}
				}else{
					//用户权限不足
					map.put("status", "fail");
					map.put(PageConstant.TIP, "用户未激活");
				}

			}else{
				//用户或者密码错误
				map.put("status", "fail");
				map.put(PageConstant.TIP, "用户或者密码错误");
			}			
		}else{
			//验证码错误
			map.put("status", "fail");
			map.put(PageConstant.TIP, "验证码错误");
		}		
		return map;	
	}
}
